package com.cens.mall.commodity.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.cens.common.utils.R;
import com.cens.mall.commodity.entity.SkuImagesEntity;
import com.cens.mall.commodity.entity.SpuInfoDescEntity;
import com.cens.mall.commodity.entity.SpuInfoEntity;
import com.cens.mall.commodity.feign.SeckillFeignService;
import com.cens.mall.commodity.service.*;
import com.cens.mall.commodity.vo.SeckillSessionVo;
import com.cens.mall.commodity.vo.SkuItemSaleAttrVo;
import com.cens.mall.commodity.vo.SkuItemVo;
import com.cens.mall.commodity.vo.SpuItemAttrGroupVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cens.common.utils.PageUtils;
import com.cens.common.utils.Query;

import com.cens.mall.commodity.dao.SkuInfoDao;
import com.cens.mall.commodity.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private SeckillFeignService seckillFeignService;
    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> skuInfoEntityQueryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            skuInfoEntityQueryWrapper.and(
                    w -> w.eq("id", key).or().like("spu_name", key)
            );
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            skuInfoEntityQueryWrapper.eq("catelog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            skuInfoEntityQueryWrapper.eq("brand_id", brandId);
        }
        String min = (String) params.get("min");
        if (StringUtils.isNotEmpty(min) && new BigDecimal(min).compareTo(BigDecimal.ZERO) > 0) {
            skuInfoEntityQueryWrapper.ge("price", min);
        }
        String max = (String) params.get("max");
        if (StringUtils.isNotEmpty(max) && new BigDecimal(max).compareTo(BigDecimal.ZERO) > 0) {
            skuInfoEntityQueryWrapper.le("price", max);
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                skuInfoEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuInfo(Long spuId) {
        return this.list(
                new QueryWrapper<SkuInfoEntity>()
                        .eq("spu_id", spuId)
        );
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture
                .supplyAsync(
                        //查询sku基本信息
                        () -> {
                            SkuInfoEntity skuInfoEntity = getById(skuId);
                            skuItemVo.setInfo(skuInfoEntity);
                            return skuInfoEntity;
                        },
                        executor
                );
        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync(
                res -> {
                    Long spuId = res.getSpuId();
                    //查询spu销售组合
                    List<SkuItemSaleAttrVo> saleAttrs = skuSaleAttrValueService.getSaleAttrsBySpuId(spuId);
                    skuItemVo.setSaleAttrs(saleAttrs);
                }, executor
        );
        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync(
                res -> {
                    Long spuId = res.getSpuId();
                    //获取spu介绍
                    SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(spuId);
                    skuItemVo.setDesc(spuInfoDescEntity);
                }, executor
        );
        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync(
                res -> {
                    Long spuId = res.getSpuId();
                    Long catalogId = res.getCatalogId();
                    //获取spu规格参数信息
                    List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(spuId, catalogId);
                    skuItemVo.setGroupAttrs(attrGroupVos);
                }, executor
        );

        //查询sku图片信息
        CompletableFuture<Void> imgsFuture = CompletableFuture.runAsync(
                () -> {
                    List<SkuImagesEntity> imagesEntities = skuImagesService.getImagesBySkuId(skuId);
                    skuItemVo.setImages(imagesEntities);
                },
                executor
        );
        //查询sku是否参与秒杀活动
        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(
                () -> {
                    R r = seckillFeignService.getSkuSeckillInfo(skuId);
                    if (r.getCode() == 0) {
                        SeckillSessionVo data = r.getData(new TypeReference<SeckillSessionVo>() {
                        });
                        skuItemVo.setSeckillSession(data);
                    }
                },executor
        );
        CompletableFuture.allOf(infoFuture,saleAttrFuture,descFuture,baseAttrFuture,imgsFuture,seckillFuture).get();
        return skuItemVo;
    }

}